package com.lvmama.rhino.web;

import com.github.pagehelper.PageInfo;
import com.lvmama.entity.system.SysUser;
import com.lvmama.rhino.base.BaseControllerSupport;
import com.lvmama.rhino.entity.BaseCondition;
import com.lvmama.rhino.pojo.Log;
import com.lvmama.rhino.service.LogService;
import com.lvmama.rhino.utils.Constants;
import com.lvmama.rhino.utils.DateUtil;
import com.lvmama.rhino.web.sso.SystemSession;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.util.*;

@Controller
@RequestMapping("returnVisit")
public class UserReturnVisitController extends BaseControllerSupport {

    private static final Logger logger = Logger.getLogger(UserReturnVisitController.class);

    @Autowired
    private LogService logService;

    /**
     * 用户回访数据展示
     *
     * @param model
     * @return
     */
    @RequestMapping("directoryShows")
    public String directoryShows(ModelMap model, BaseCondition baseCondition) {
        FTPClient ftpClient = getFTPClient();
        String completeDirectory = Constants.getFtpConfig("ftp.partDirectory");
        List<String> directoryList = new ArrayList<String>();
        try {
            boolean flag = ftpClient.changeWorkingDirectory(completeDirectory);//转移到FTP服务器目录
            logger.info("数据展示时,转移到FTP服务器目录" + completeDirectory + "是否成功:" + flag);
            if (!flag) {
                ftpClient.disconnect();
            }
            ftpClient.enterLocalPassiveMode();//开通一个端口来传输数据
            FTPFile[] fs = ftpClient.listFiles();
            logger.info("数据展示时目录大小:" + fs.length);
            for (int i = 0; i < fs.length; i++) {
                String directoryName = fs[i].getName();
                directoryList.add(directoryName);
            }
            Collections.sort(directoryList, new Comparator<String>() {
                @Override
                public int compare(String o1, String o2) {
                    return Integer.parseInt(o2) - Integer.parseInt(o1);
                }
            });
            if (directoryList.size() > 30) {
                directoryList = directoryList.subList(0, 30);
            }
            for (int i = 0; i < directoryList.size(); i++) {
                String str = DateUtil.formatString(directoryList.get(i), "yyyyMMdd", "yyyy-MM-dd");
                directoryList.set(i, str);
            }

            int pageNum = baseCondition.getPage();
            int pageSize = baseCondition.getPageSize();
            int start = (pageNum - 1) * pageSize;
            int end = pageNum * pageSize;
            int dataCount = directoryList.size();
            if (end > dataCount) {
                end = dataCount;
            }
            List<String> date1 = directoryList.subList(start, end);
            PageInfo<String> page = new PageInfo<String>(date1);
            page.setPageNum(pageNum);
            page.setPageSize(pageSize);
            int startRow = (pageNum - 1) * pageSize + 1;//开始条数
            page.setStartRow(startRow);
            page.setEndRow(end);//结束条数
            page.setFirstPage(1);
            page.setPrePage(pageNum - 1);//上一页
            page.setNextPage(pageNum + 1);//下一页

            page.setTotal(dataCount);
            int add = dataCount % pageSize == 0 ? 0 : 1;
            int sum = dataCount / pageSize + add;
            page.setPages(sum);
            page.setLastPage(sum);
            model.addAttribute("page", page);
            model.addAttribute("date1", date1);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (ftpClient.isConnected()) {
                try {
                    ftpClient.disconnect();
                } catch (IOException ioe) {
                }
            }
        }
        SysUser user = SystemSession.getUser();
        model.addAttribute("currentUser", user);
        return "application/directoryShows";
    }

    /**
     * 获取并连接FTP服务器
     *
     * @return
     */
    public FTPClient getFTPClient() {
        String host = Constants.getFtpConfig("ftp.host");//ip地址
        int port = Integer.parseInt(Constants.getFtpConfig("ftp.port"));//端口号
        String username = Constants.getFtpConfig("ftp.username");//用户名
        String password = Constants.getFtpConfig("ftp.password");//密码
        logger.info("连接FTP服务器host:" + host + ",port:" + port + ",username:" + username + ",password:" + password);

        FTPClient ftpClient = new FTPClient();
        try {
            int reply;
            ftpClient.connect(host, port);
            boolean isLogin = ftpClient.login(username, password);
            logger.info("FTP服务器isLogin:" + isLogin);
            reply = ftpClient.getReplyCode();
            if (!FTPReply.isPositiveCompletion(reply)) {
                ftpClient.disconnect();
                return null;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return ftpClient;
    }


    /**
     * 验证目录是否存在
     *
     * @param request
     * @param response
     * @param directory
     * @return
     */
    @RequestMapping("inspectionDirectory")
    @ResponseBody
    public Map<String, Object> inspectionDirectory(HttpServletRequest request, HttpServletResponse response, String directory) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        directory = DateUtil.formatString(directory, "yyyy-MM-dd", "yyyyMMdd");
        String completeDirectory = Constants.getFtpConfig("ftp.partDirectory") + directory;
        FTPClient ftpClient = getFTPClient();
        try {
            boolean flag = ftpClient.changeWorkingDirectory(completeDirectory);//转移到FTP服务器目录
            logger.info("目录" + directory + "是否存在:" + flag);
            if (!flag) {
                ftpClient.disconnect();
                resultMap.put("message", "数据不存在！");
                return resultMap;
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (ftpClient.isConnected()) {
                try {
                    ftpClient.disconnect();
                } catch (IOException ioe) {
                }
            }
        }
        resultMap.put("message", "1");
        return resultMap;
    }


    /**
     * 下载文件
     *
     * @param request
     * @param response
     * @param directory
     */
    @RequestMapping("actionDownload")
    public void actionDownload(HttpServletRequest request, HttpServletResponse response, String directory, String loginName) {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("multipart/form-data");

        FTPClient ftpClient = getFTPClient();
        directory = DateUtil.formatString(directory, "yyyy-MM-dd", "yyyyMMdd");
        String completeDirectory = Constants.getFtpConfig("ftp.partDirectory") + directory;
        String fileName = Constants.getFtpConfig("ftp.fileName");

        OutputStream os = null;
        boolean isDownload = false;
        try {
            boolean flag = ftpClient.changeWorkingDirectory(completeDirectory);//转移到FTP服务器目录
            if (!flag) {
                ftpClient.disconnect();
                return;
            }
            ftpClient.enterLocalPassiveMode();
            FTPFile[] fs = ftpClient.listFiles();
            for (int i = 0; i < fs.length; i++) {
                if (fs[i].getName().equals(fileName)) {
//                    String saveAsFileName = new String(fs[i].getName().getBytes("UTF-8"), "ISO8859-1");
                    response.setHeader("Content-Disposition", "attachment;fileName=" + directory + ".csv");
                    os = response.getOutputStream();
                    isDownload = ftpClient.retrieveFile(fs[i].getName(), os);
                    logger.info("目录" + directory + "下文件是否下载成功:" + isDownload);
                    os.flush();
                    os.close();
                    break;
                }
            }
            ftpClient.logout();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (ftpClient.isConnected()) {
                try {
                    ftpClient.disconnect();
                } catch (IOException ioe) {
                }
            }
        }
        if (isDownload) {
            if (loginName != null && !"".equals(loginName)) {
                Log log = new Log();
                log.setTitle("");
                log.setRemoteAddr(getRemoteAddr(request));
                log.setRequestUri(request.getRequestURI());
                log.setParams("directory=" + directory);
                log.setOperator(loginName);
                log.setCreateDate(new Date());
                logService.saveLog(log);
            }
        }

    }

    /**
     * 获取用户真实IP地址
     *
     * @param request
     * @return
     */
    public String getRemoteAddr(HttpServletRequest request) {
        String remoteAddr = request.getHeader("X-Real-IP");
        if (StringUtils.isBlank(remoteAddr)) {
            remoteAddr = request.getHeader("X-Forwarded-For");
        } else if (StringUtils.isBlank(remoteAddr)) {
            remoteAddr = request.getHeader("Proxy-Client-IP");
        } else if (StringUtils.isBlank(remoteAddr)) {
            remoteAddr = request.getHeader("WL-Proxy-Client-IP");
        }
        return remoteAddr != null ? remoteAddr : request.getRemoteAddr();
    }
}
